package org.example.what_mall.service.impl;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.what_mall.dto.CommentDTO;
import org.example.what_mall.dto.CommentForm;
import org.example.what_mall.dto.CommentListDTO;
import org.example.what_mall.dto.MessageForm;
import org.example.what_mall.entity.*;
import org.example.what_mall.enums.MessageState;
import org.example.what_mall.exception.GlobalException;
import org.example.what_mall.mapper.*;
import org.example.what_mall.service.ICommentService;
import org.example.what_mall.util.RedisConstant;
import org.example.what_mall.vo.MsgReplyVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImpl implements ICommentService {
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SpecMapper specMapper;
    @Autowired
    private ReplyMapper replyMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Transactional
    @Override
    public void askGoodsMsg(MessageForm form) {
        if(form == null || form.getMsg() == null || form.getMsg().trim().isEmpty()){
            throw new GlobalException(400, "问题内容为空");
        }

        String keyword = RedisConstant.USER_TOKE_PREFIX + form.getToken();
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(keyword);
        Integer userId = Integer.parseInt(entries.get("id").toString());

        Message msg = Message.builder()
                .state(MessageState.UNREPLIED.getCode())
                .goodsId(form.getGoodsId())
                .content(form.getMsg())
                .time(LocalDateTime.now())
                .userId(userId)
                .build();
        messageMapper.insert(msg);
    }

    @Override
    public List<MsgReplyVO> getGoodsMsg(Integer id) {
        List<Message> messages = messageMapper.selectList(new LambdaQueryWrapper<Message>().eq(Message::getGoodsId, id));
        List<MsgReplyVO> messageVOS = new ArrayList<>();
        for (Message message : messages) {
            User user = userMapper.selectById(message.getUserId());
            if(user == null) continue;
            Reply reply = replyMapper.selectOne(new LambdaQueryWrapper<Reply>().eq(Reply::getMessageId, message.getId()));
            messageVOS.add(new MsgReplyVO(message.getId(), message.getContent(), user.getNickname(), message.getTime(), reply));
        }
        return messageVOS;
    }

    @Transactional
    @Override
    public void sendComment(CommentForm form) {
        if(form == null || form.getContent() == null || form.getContent().trim().isEmpty()){
            throw new GlobalException(400, "评价内容为空");
        }

        String keyword = RedisConstant.USER_TOKE_PREFIX + form.getToken();
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(keyword);
        Integer userId = Integer.parseInt(entries.get("id").toString());

        Comment comment = Comment.builder()
                .userId(userId)
                .goodsDetailId(form.getGoodsDetailId())
                .score(form.getScore())
                .content(form.getContent())
                .goodsId(form.getGoodsId())
                .time(LocalDateTime.now())
                .build();
        commentMapper.insert(comment);
    }

    @Override
    public CommentListDTO getGoodsComment(Integer goodsId) {
        List<Comment> comments = commentMapper.selectList(new LambdaQueryWrapper<Comment>().eq(Comment::getGoodsId, goodsId));
        int rate = 0;
        CommentListDTO commentListDTO = new CommentListDTO();
        commentListDTO.setCommentList(new ArrayList<>());

        if(comments == null || comments.isEmpty()){
            commentListDTO.setRate(rate);
            return commentListDTO;
        }

        for (Comment comment : comments) {
            rate += comment.getScore();

            User u = userMapper.selectById(comment.getUserId());
            if(u == null) continue;
//            Spec spec = specMapper.selectById(comment.getGoodsDetailId());
//            if(spec == null) continue;

            CommentDTO commentDTO = CommentDTO.of(u, comment);
            commentListDTO.getCommentList().add(commentDTO);
        }
        rate /= comments.size();
        commentListDTO.setRate(rate);
//        System.out.println(commentListDTO.getCommentList());

        return commentListDTO;
    }
}
